<template>
  <div class="my-page">
    <div class="user-profile">
      <div class="avatar-container" @click="handleAvatarClick">
        <img :src="userInfo.avatar || defaultAvatar" class="avatar" />
        <div class="avatar-overlay">
          <span>更换头像</span>
        </div>
      </div>

      <div class="user-info">
        <h2>{{ userInfo.account || "未设置账户名" }}</h2>
        <p class="user-name">{{ userInfo.name || "未设置名称" }}</p>
        <p class="user-type">{{ userType }}</p>
      </div>
    </div>

    <div class="user-intro">
      <h3>个人介绍</h3>
      <p>{{ userInfo.introduction || "暂无介绍" }}</p>
    </div>

    <div class="user-intro">
      <h3>创建时间</h3>
      <p>{{ userInfo.created_time || "暂无创建时间" }}</p>
    </div>

    <div class="action-list">
      <div class="action-item" @click="editProfile">
        <i class="icon-edit"></i>
        <span>编辑个人资料</span>
        <van-icon name="setting" />
      </div>
      <div class="action-item" @click="changePassword">
        <i class="icon-lock"></i>
        <span>修改密码</span>
        <img style="width: 20px; height: 20px" :src="passWordIcon" />
      </div>
      <div class="action-item" @click="loginOut">
        <i class="icon-lock"></i>
        <span>退出登录</span>
        <img style="width: 20px; height: 20px" :src="quitIcon" />
      </div>
    </div>

    <input
      type="file"
      ref="fileInput"
      accept="image/*"
      style="display: none"
      @change="uploadAvatar"
    />

    <!-- 修改密码弹窗 -->
    <van-popup
      v-model:show="showPasswordDialog"
      round
      position="bottom"
      :style="{ height: '60%' }"
      closeable
    >
      <div class="password-form-container">
        <h2 class="form-title">修改密码</h2>

        <van-form @submit="submitPasswordChange">
          <!-- 旧密码 -->
          <van-field
            v-model="passwordForm.oldPassword"
            name="oldPassword"
            :type="showOldPassword ? 'text' : 'password'"
            label="旧密码"
            placeholder="请输入旧密码"
            :rules="[{ required: true, message: '请输入旧密码' }]"
          >
            <template #right-icon>
              <van-icon
                :name="showOldPassword ? 'eye-o' : 'closed-eye'"
                @click="showOldPassword = !showOldPassword"
                class="password-eye-icon"
              />
            </template>
          </van-field>

          <!-- 新密码 -->
          <van-field
            v-model="passwordForm.newPassword"
            name="newPassword"
            :type="showNewPassword ? 'text' : 'password'"
            label="新密码"
            placeholder="请输入新密码"
            :rules="[{ required: true, message: '请输入新密码' }]"
          >
            <template #right-icon>
              <van-icon
                :name="showNewPassword ? 'eye-o' : 'closed-eye'"
                @click="showNewPassword = !showNewPassword"
                class="password-eye-icon"
              />
            </template>
          </van-field>

          <!-- 确认新密码 -->
          <van-field
            v-model="passwordForm.confirmPassword"
            name="confirmPassword"
            :type="showConfirmPassword ? 'text' : 'password'"
            label="确认密码"
            placeholder="请再次输入新密码"
            :rules="[
              { required: true, message: '请再次输入新密码' },
              {
                validator: validateConfirmPassword,
                message: '两次输入的密码不一致',
              },
            ]"
          >
            <template #right-icon>
              <van-icon
                :name="showConfirmPassword ? 'eye-o' : 'closed-eye'"
                @click="showConfirmPassword = !showConfirmPassword"
                class="password-eye-icon"
              />
            </template>
          </van-field>

          <div class="form-buttons">
            <van-button
              round
              block
              type="primary"
              native-type="submit"
              :loading="submitting"
            >
              确认修改
            </van-button>
            <van-button
              round
              block
              type="default"
              @click="showPasswordDialog = false"
              style="margin-top: 12px"
            >
              取消
            </van-button>
          </div>
        </van-form>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, reactive } from "vue";
import store from "@/store";
import passWordIcon from "@/assets/password.png";
const userInfo = ref({});
const fileInput = ref(null);
const defaultAvatar = "/path/to/default-avatar.png"; // 设置默认头像路径
import { getToken } from "@/utils/auth";
import host from "@/utils/host";
import quitIcon from "@/assets/quit.png";
import { showSuccessToast, showFailToast } from "vant";
import { setPassword } from "@/api/user";
import { useRouter, useRoute } from "vue-router";

const route = useRoute();
const router = useRouter();
onMounted(() => {
  // 从store获取用户信息
  getUserInfo();
});

const getUserInfo = () => {
  // 假设store中有获取用户信息的getter
  // console.log(store.getters);
  const { roles, name, avatar, account } = store.getters;
  const created_time = store.getters.created_time.replace("T", " ");
  userInfo.value = { roles, name, created_time, avatar, account };
};

const userType = computed(() => {
  if (store.getters.roles.includes("admin")) {
    return "管理员";
  } else {
    return "普通用户";
  }
});

const handleAvatarClick = () => {
  // 触发文件选择
  fileInput.value.click();
};

const uploadAvatar = async (event) => {
  try {
    const token = getToken();
    const port = process.env.NODE_ENV == "development" ? 9080 : 80;
    const url = `http://${host}:${port}/elearning/user/uploadAvatar`;
    const file = event.target.files[0];
    if (!file) return;

    // 创建FormData并发送到服务器
    const formData = new FormData();
    formData.append("file", file); // 参数名为"file"匹配Controller参数
    formData.append("token", token); // token作为请求参数

    // 使用fetch API发送POST请求
    const response = await fetch(url, {
      method: "POST",
      body: formData,
    });

    if (!response.ok) {
      throw new Error("网络响应异常");
    }

    const result = await response.json();

    // 处理返回的Result对象
    if (result && result.code === 20000 && result.data) {
      userInfo.value.avatar = result.data; // 使用result.data获取URL
      // 更新store中的头像
      store.commit("user/SET_AVATAR", result.data);
    } else {
      console.error("上传失败:", result.message || "未知错误");
    }
  } catch (error) {
    console.error("上传出错:", error);
  } finally {
    // 清空文件输入，允许选择相同文件
    event.target.value = "";
  }
};

const editProfile = () => {
  // 跳转到编辑资料页面或打开编辑弹窗
  console.log("编辑个人资料");
};

// 修改密码相关状态
const showPasswordDialog = ref(false);
const submitting = ref(false);
const passwordForm = reactive({
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});

// 密码显示状态
const showOldPassword = ref(false);
const showNewPassword = ref(false);
const showConfirmPassword = ref(false);

// 验证确认密码是否匹配
const validateConfirmPassword = (val) => {
  return val === passwordForm.newPassword;
};

// 修改密码
const changePassword = () => {
  showPasswordDialog.value = true;
  // 重置表单
  passwordForm.oldPassword = "";
  passwordForm.newPassword = "";
  passwordForm.confirmPassword = "";
  showOldPassword.value = false;
  showNewPassword.value = false;
  showConfirmPassword.value = false;
};

// 提交密码修改
const submitPasswordChange = async () => {
  submitting.value = true;

  try {
    // 假设这是您的API调用
    const data = {
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword,
    };
    setPassword(data).then(() => {
      showSuccessToast({
        message: "密码修改成功",
      });
      // 重置passwordFrom
      passwordForm.oldPassword = "";
      passwordForm.newPassword = "";
      passwordForm.confirmPassword = "";
      setTimeout(() => {
        store.dispatch("user/logout").then(() => {
          router.push(`/my/login?redirect=${route.fullPath}`);
        });
      }, 1000);
    });
  } catch (error) {
    console.error("修改密码出错", error);
    showFailToast("修改密码失败，请稍后再试");
  } finally {
    submitting.value = false;
  }
};

const loginOut = async () => {
  // 处理退出登录
  if (!getToken()) {
    //直接返回登陆
    router.push("/login");
    return;
  }
  await store.dispatch("user/logout");
  router.push(`/my/login?redirect=${route.fullPath}`);
};
</script>

<style scoped>
.my-page {
  padding: 20px;
  max-width: 100%;
  box-sizing: border-box;
  background-color: #f8f9fa;
  min-height: 100vh;
}

.user-profile {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  background-color: white;
  padding: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.avatar-container {
  position: relative;
  width: 90px;
  height: 90px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 20px;
  border: 3px solid #f0f0f0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  font-size: 12px;
  padding: 6px 0;
  text-align: center;
  transition: all 0.3s ease;
}

.avatar-container:hover .avatar-overlay {
  background: rgba(0, 0, 0, 0.75);
}

.user-info {
  flex: 1;
}

.user-info h2 {
  margin: 0 0 8px 0;
  font-size: 20px;
  color: #333;
}

.user-name,
.user-type {
  margin: 4px 0;
  font-size: 14px;
  color: #666;
}

.user-type {
  display: inline-block;
  background-color: #e6f7ff;
  color: #1890ff;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  margin-top: 8px;
}

.user-intro {
  background: white;
  padding: 16px;
  border-radius: 12px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.user-intro h3 {
  margin: 0 0 10px 0;
  font-size: 16px;
  color: #333;
  position: relative;
  padding-left: 12px;
}

.user-intro h3::before {
  content: "";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 16px;
  background-color: #1890ff;
  border-radius: 2px;
}

.user-intro p {
  margin: 0;
  font-size: 14px;
  color: #555;
  line-height: 1.5;
}

.action-list {
  margin-top: 20px;
}

.action-item {
  display: flex;
  align-items: center;
  padding: 16px;
  margin-bottom: 12px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.action-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.action-item i {
  margin-right: 12px;
  font-size: 20px;
  color: #666;
}

.action-item span {
  font-size: 16px;
  color: #333;
}

.action-item img,
.action-item .van-icon {
  margin-left: auto;
  margin-right: 8px;
  color: #999;
}

.password-form-container {
  padding: 24px 20px;
}

.form-title {
  text-align: center;
  margin-bottom: 28px;
  font-size: 20px;
  font-weight: 500;
  color: #333;
}

.form-buttons {
  margin-top: 28px;
  padding: 0 16px;
}

.form-buttons .van-button {
  height: 44px;
  font-size: 16px;
}

.form-buttons .van-button--primary {
  background-color: #1890ff;
  border-color: #1890ff;
}

.password-eye-icon {
  font-size: 20px;
  color: #969799;
}

:deep(.van-field__right-icon) {
  height: 100%;
  display: flex;
  align-items: center;
  cursor: pointer;
}

:deep(.van-field__label) {
  width: 90px;
}

:deep(.van-popup) {
  border-radius: 16px 16px 0 0;
}

:deep(.van-field) {
  padding: 12px 16px;
}
</style>
